import { goToPage, setObjToStorageTemp } from '../utils/index'
import Constant from '../utils/constant'

// eslint-disable-next-line one-var
const Fly = require('flyio/dist/npm/fly'),
  fly = new Fly()
// 设置超时
fly.config.timeout = 30000

// 添加请求拦截器
// fly.interceptors.request.use((request) => {
//   // 给所有请求添加自定义header
//   const token = getStorageSync(Constant.STORAGE_KEY.TOKEN)
//   request.headers.token = token
//   return request
// })

/**
 * Request服务封装
 */
export default {
  sendRequest
}

function sendRequest () {
  return {
    _sucCallback: null,
    _failCallback: null,
    _method: 'GET',
    _data: {},
    _header: { 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8' },
    _url: '',
    'send' () {
      fly.request(this._url, this._data, {
        method: this._method,
        headers: this._header
      }).then((res) => {
        const error = httpHandlerError(res, this._failCallback)
        if (error) {
          return
        }
        this._sucCallback(res)
      }).catch((res) => {
        httpHandlerError(res, this._failCallback)
      })
      return this
    },
    'success' (callback) {
      this._sucCallback = callback
      return this
    },
    'fail' (callback) {
      this._failCallback = callback
      return this
    },
    'url' (url) {
      this._url = url
      return this
    },
    'data' (data) {
      this._data = data
      return this
    },
    'method' (method) {
      this._method = method
      return this
    },
    'header' (header) {
      this._header = header
      return this
    },
    'showLoading' (showLoading) {
      this._showLoading = showLoading
      return this
    }
  }
}

/**
 * Info 请求完成后返回信息
 * callBack 回调函数
 * errTip 自定义错误信息
 */
function httpHandlerError (info, callBack) {
  /** 请求成功，退出该函数 可以根据项目需求来判断是否请求成功。这里判断的是status为200的时候是成功 */
  // eslint-disable-next-line one-var,no-unused-vars
  let errTip,
    haveError = true
  if (info.status === 200) {
    if (info.data.code === undefined) {
      haveError = true
    } else if (info.data.code === 'success' || info.data.code === 0) {
      haveError = false
    } else if (info.data.code === 401) {
      setObjToStorageTemp(Constant.STORAGE_KEY.USER_INFO, null)
      // eslint-disable-next-line no-undef
      setObjToStorageTemp(Constant.STORAGE_KEY.BEFORE_AUTH_PAGE, location.href)
      goToPage(Constant.PAGE.AUTH, true)
      haveError = true
      errTip = null
    } else {
      haveError = true
      errTip = info.data.msg
    }
  } else {
    errTip = `网络请求出现了错误【${info.status}】`
    haveError = true
  }

  if (haveError) {
    /** 发生错误信息时，如果有回调函数，则执行回调 */
    if (callBack) {
      callBack(info)
    } else {
    }
  }
  return haveError
}
